/**
 * see: src\components\DataTable\DataTable.js
 */
import React, { useEffect, useState, useCallback } from 'react';
import { Card, Table } from 'antd';
// import styles from './DataTable.less';
import { itemRender } from '@/utils/utils';

const LazyTablePage = ({
    columns,
    getData,
    rowKey,
    updateQuery,
    cardProps
}) => {
    const DEFAULT_CURRENT = 1;
    const DEFAULT_PAGESIZE = 10;
    const [data, setData] = useState([]);
    const [current, setCurrent] = useState(DEFAULT_CURRENT);
    const [pageSize, setPageSize] = useState(DEFAULT_PAGESIZE);
    const [total, setTotal] = useState(0);
    const [filters, setFilters] = useState({});
    const [sorters, setSorters] = useState({});
    const [loading, setLoading] = useState(false);
    const handleTable = (pagination, filtersArg, sorts) => {
        setSorters(sorts);
        setFilters(filtersArg);
        setCurrent(pagination.current);
        setPageSize(pagination.pageSize);
    };
    const fetchList = useCallback(async () => {
        setLoading(true);
        const result = await getData({
            current,
            pageSize,
            filters,
            sorters
        });
        setData(result.data);
        setCurrent(result.current);
        setPageSize(result.pageSize);
        setTotal(result.total);
        setLoading(false);
        updateQuery();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [current, pageSize, filters, sorters]);
    useEffect(() => {
        fetchList();
    }, [fetchList]);
    const table = (
        <Table
            className="vv-dataTable-table"
            columns={columns}
            dataSource={data}
            loading={loading}
            onChange={handleTable}
            rowKey={rowKey}
            pagination={{
                current,
                pageSize,
                total,
                showSizeChanger: true,
                itemRender,
                showTotal: totalStr => `${totalStr} items`
            }}
        />
    );
    return (
        <Card className="vv-dataTable" bordered={false} {...cardProps}>
            {table}
        </Card>
    );
};

export default LazyTablePage;
